define(['jquery', 'bootstrap', 'backend', 'table', 'form', 'template','layer'], function ($, undefined, Backend, Table, Form, Template,Layer) {

  var Controller = {
      index: function () {
          var table = $("#table");

          $(document).on('click', '.thisaddtabs', function (e) {
              Backend.api.addtabs(Backend.api.replaceids(this, $(this).attr('url')), $(this).attr("title"));
              return false;
          });

          $(document).on('click','.btn-import',function(e){
              require(['upload'], function (Upload) {
                  Upload.api.plupload($(".btn-import", "#toolbar"), function (data, ret) {
                    $.ajax({
                        type: "post",
                        url: "/cms.php/auth.admin/import.html",
                        data: {file: data.url},
                        dataType: 'JSON',
                        success: function (datak) {
                            location.reload();
                        },
                        error: function () {
                            alert('编辑失败');
                        },
                        complete: function () {

                        }
                    });
                  });
              });
          });
          $(document).on('click', '#chkSelectAll', function (e) {
              $(this).prop("checked","checked");
              $("#table input[name=btSelectItem]").each(function(){
                  $(this).prop("checked",!$(this).prop("checked"));
              });
              return false;
          });
          $(document).on('click', 'input[name=btSelectItem]',function (e) {
              var ll = $("input[name=btSelectItem]:checked").length;
              if(ll > 0){
                  if(ll == 1){
                      $(".btn-edit").removeClass('disabled');
                  }else{
                      $(".btn-edit").addClass('disabled');
                  }
                  $(".btn-del").removeClass('disabled');
                  if(typeof($(".btn-more"))!='undefined'){
                      $(".btn-more").removeClass('disabled');
                  }
              }else{
                  $(".btn-edit").addClass('disabled');
                  $(".btn-del").addClass('disabled');
                  if(typeof($(".btn-more"))!='undefined'){
                      $(".btn-more").addClass('disabled');
                  }
              }
          });
          $(".btn-edit").on("click",function(e){
              e.preventDefault();
              var chenked = $("input[name='btSelectItem']:checked");
              Backend.api.addtabs(Backend.api.replaceids(this, 'auth.admin/edit?ids='+chenked[0].value),'编辑');
              return false;
          });
          $(".btn-del").on("click",function (e) {
              e.preventDefault();
              var chenked = $("input[name='btSelectItem']:checked");
              var ids = "";
              for(var i=0;i<chenked.length;i++){
                  ids += chenked[i].value+",";
              }
              if(chenked.length==0){
                  var index2 = Layer.confirm('请选择字段','请选择');

              }else{
                  var id = $(this).data("id");
                  var that = this;
                  var index = Layer.confirm(
                      __('Are you sure you want to delete this item?'),
                      {icon: 3, title: __('Warning'), shadeClose: true},
                      function () {
                          $.ajax({
                              type: "post",
                              url: "/cms.php/auth.admin/dels.html",
                              data: {ids:ids},
                              dataType: 'JSON',
                              success: function (data, status) {
                                  if (status == "success") {
                                      Layer.close(index);
                                      location.reload();
                                  }
                              },
                              error: function () {
                                  alert('编辑失败');
                              },
                              complete: function () {

                              }
                          });
                      }
                  );
              }

          });
          $(".btn-delone").on("click",function(e){
              var ids = $(this).prop("title");
              var index = Layer.confirm(
                  __('Are you sure you want to delete this item?'),
                  {icon: 3, title: __('Warning'), shadeClose: true},
                  function () {
                      $.ajax({
                          type: "post",
                          url: "/cms.php/auth.admin/del.html",
                          data: {ids:ids},
                          dataType: 'JSON',
                          success: function (data, status) {
                              if (status == "success") {
                                  Layer.close(index);
                                  location.reload();
                              }
                          },
                          error: function () {
                              //alert('编辑失败');
                          },
                          complete: function () {

                          }
                      });
                  }
              );
          });
          //表格切换
          $("#toggleview").on('click', function (e) {
                if($("#table thead").is(":hidden")){
                    //转换table视图
                    $("#table thead").show();
                    var ss = '';
                    $("#datalist tr").each(function(i){
                        var obj = $(this);
                        ss += '<tr data-index="'+i+'">';
                            $.each(eval(pagedata.columns),function(k,v){
                                if(v.isshowlist==1){
                                    switch(k.toLowerCase()){
                                        case 'itemid':
                                            ss += '<td class="bs-checkbox" columnname="'+v.columnenname+'">';
                                            ss += '<input data-index="'+i+'" name="btSelectItem" type="checkbox" value="'+obj.find("div.card-view [columnname='"+k.toLowerCase()+"'] input[type='checkbox']").val()+'" />';
                                        break;
                                        default:
                                            var s4 = obj.find("div.card-view[columnname='"+v.columnenname+"'] span.value").html();
                                            if(typeof(s4)!='undefined'){
                                                ss += '<td columnname="'+k+'">';
                                                ss += s4;
                                            }
                                    }
                                    ss += '</td>';
                                }
                            });
                            ss += '<td columnname="caozuo">';
                                ss += obj.find("div.card-view[columnname='caozuo'] span.value").html();
                            ss += '</td>';
                        ss += '</tr>';
                    });
                    $("#datalist").html(ss);
                }else{
                    //转换cardview视图
                    $("#table thead").hide();
                    var ss = '';
                    $("#datalist tr").each(function(i){
                        var obj = $(this);
                        ss += '<tr data-index="0">';
                        ss += '<td>';
                            ss += '<div class="card-views">';
                            $.each(eval(pagedata.columns),function(k,v){
                                if(v.isshowlist==1){
                                    ss += '<div class="card-view" columnname="'+v.columnenname+'">';
                                    switch(k.toLowerCase()){
                                        case 'itemid':
                                            ss += '<input data-index="'+i+'" name="btSelectItem" type="checkbox" value="'+obj.find("td[columnname='"+k.toLowerCase()+"'] input[type='checkbox']").val()+'" />';
                                        break;
                                        default:
                                            var s4 = obj.find("td[columnname='"+k+"']").html();
                                            if(typeof(s4)!='undefined'){
                                                ss += '<span class="title">'+v.columnname+'</span><span class="value">'+s4+'</span>';
                                            }
                                    }
                                    ss += '</div>';
                                }
                            });
                            ss += '<div class="card-view" columnname="caozuo">';
                                ss += '<span class="title" style="text-align: center; vertical-align: middle; ">操作</span>';
                                ss += '<span class="value">'+obj.find("td[columnname='caozuo']").html()+'</span>';
                              //<span class="value"><a href="/admin/auth/adminlog/detail/ids/1355" class="btn btn-info btn-xs btn-detail btn-dialog" title="详情"><i class="fa fa-list"></i> 详情</a> <a href="javascript:;" class="btn btn-xs btn-danger btn-delone" title=""><i class="fa fa-trash"></i></a></span>
                            ss += '</div>';
                            ss += '</div>';
                        ss += '</td>';
                        ss += '</tr>';
                    });
                    $("#datalist").html(ss);
                }
            });
          //窗体太窄，自动缩小。
          if($(window).width()<768){
              $("#toggleview").trigger('click');
          }
          $(window).resize(function(){
              if($(window).width()<=768){
                  if(!$("#table thead").is(":hidden")){
                    $("#toggleview").trigger('click');
                  }
              }
              if($(window).width()>768){
                  if($("#table thead").is(":hidden")){
                    $("#toggleview").trigger('click');
                  }
              }
          });

          Controller.api.bindevent();
      },
      add: function () {

          $(document).on("change","select[name='province[]']",function(e){
              var s = $(this).data("relate");
              $.ajax({
                  type: "post",
                  url: "ajax/city.html",
                  data: {pid:$(this).val()},
                  dataType: 'JSON',
                  success: function (ret) {
                      var str = '';
                      str += '<option value="0">请选择</option>';
                      $.each(eval(ret), function (k1, v1) {
                          $.each(eval(v1), function (k, v) {
                              str += '<option value="' + v.itemid + '"';
                              if(v.selected==1){
                                  str += ' selected="selected">';
                              }else{
                                  str += '>';
                              }
                              str += v.name;
                              str += '</option>';
                          });
                      });
                      $("#"+s).html(str);
                      $("#"+s).selectpicker('refresh');
                  },
                  error: function () {alert('编辑失败');},
                  complete: function () {}
              });
          });

          Controller.api.bindevent();
      },
      edit: function () {
        $(document).on("change","select[name='province[]']",function(e){
            var s = $(this).data("relate");
            var citys = $("#"+s).val();
            $.ajax({
                type: "post",
                url: "ajax/city.html",
                data: {pid:$(this).val(),cityids:citys},
                dataType: 'JSON',
                success: function (ret) {
                    var str = '';
                    str += '<option value="0">请选择</option>';
                    
                    $.each(eval(ret), function (k1, v1) {
                          $.each(eval(v1), function (k, v) {
                              str += '<option value="' + v.itemid + '"';
                              if(v.selected==1){
                                  str += ' selected="selected">';
                              }else{
                                  str += '>';
                              }
                              str += v.name;
                              str += '</option>';
                          });
                    });
                    $("#"+s).html(str);
                    $("#"+s).selectpicker('refresh');
                },
                error: function () {alert('编辑失败');},
                complete: function () {}
            });
        });
        $(".returnback").click(function(){
            history.back();
        });
        Controller.api.bindevent();
      },
      select: function(){
          var table = $("#table");
          $(".btn-chooseone").on("click",function(e){
              console.log($(this).attr('title'));
              console.log($(this).attr('alt'));
              Fast.api.close({itemid:$(this).attr('title'),name:$(this).attr('alt'), multiple: false});
          });
          /*
          .btn-chooseone': function (e, value, row, index) {
              var multiple = Backend.api.query('multiple');
              multiple = multiple == 'true' ? true : false;
              Fast.api.close({url: row.url, multiple: false});
          }
          */
          Controller.api.bindevent();
      },
      api: {
          bindevent: function () {
              Form.api.bindevent($("form[role=form]"));
          }
      }
  };
  return Controller;
});
